package com.powernode.interceptor;

import com.powernode.constant.CommonConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class FeignInterceptor implements RequestInterceptor {
    /**
     *判断是哪种格式，如果是存在token的，则不需要添加token
     * 如果是客户端模式 则需要手动添加token
     * @param requestTemplate feign发送模板
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader(CommonConstant.TOKEN_HEADER);
        if (StringUtils.hasText(token)) {
            requestTemplate.header(CommonConstant.TOKEN_HEADER, token);
            return;
        }
        requestTemplate.header(CommonConstant.TOKEN_HEADER, CommonConstant.TOKEN_CLIENT);
    }
}
